package cn.swu.lyx.homework1

import android.view.LayoutInflater
import android.view.TextureView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class MilkTeaAdapter(val milkTeas:ArrayList<MilkTea>):RecyclerView.Adapter<MilkTeaAdapter.MilkTeaViewHolder>(){
    //ViewHolder是为了对控件实例进行缓存 就不需要每次都通过findViewById来获取控件实例
    inner class MilkTeaViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        //俩种写法
        val name:TextView=itemView.findViewById(R.id.name)
        val description=itemView.findViewById<TextView>(R.id.description)
        val img:ImageView=itemView.findViewById(R.id.image)
    }

    //加载布局 创建MilkTeaViewHolder实例
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MilkTeaViewHolder {
        val view=LayoutInflater.from(parent.context).inflate(R.layout.item_milktea,parent,false)
        return MilkTeaViewHolder(view)
    }

    //对子项赋值，每个子项滚动到屏幕上时执行，position是得到当前MilkTea实例再将其相关信息设置到MilkTeaViewHolder的TextView和imageView
    override fun onBindViewHolder(holder: MilkTeaViewHolder, position: Int) {
        val milkTea=milkTeas[position]
        holder.name.text=milkTea.name
        holder.description.text=milkTea.description
        holder.img.setImageResource((milkTea.image))
    }

    //告诉RecycleView到底有多少子项
    override fun getItemCount(): Int {
        return milkTeas.size
    }
}